<?php
namespace Home\Model;

use Home\Common\BaseModel;
use Home\Controller\PayController;
use \Think\Db;
use Think\Model;

class CartsModel extends BaseModel
{

    // 默认 会员ID
    // public $member_id = 714;


    /**
     * @return array加入购物车
     */
    public function addCart($member_id)
    {

        if (empty($member_id)) {
            //return array('msg'=>'未登录，请登录！','status'=>-1);
            $this->ajaxReturn(array('status' => 0, 'url' => url('Login/index'), 'msg' => '还未登录，请登录！'));
        }


        $isCheck = 1;
        $pid = (int)I('post.pid');
        $local_id = (int)I('post.local_id');
        $goods_id = (int)I('post.goods_id');
        $spid = (int)I('post.spid');
        $cartNum = I('post.buyNum');
        //ps 加入购物车增加减少动作
        $action = I('post.action', '', 'htmlspecialchars');


        $AddData = array('pid' => $pid, 'local_id' => $local_id, 'goods_id' => $goods_id, 'member_id' => $member_id, 'spid' => $spid, 'cartNum' => $cartNum);

        //当该用户在购物车，是否有该商品
        $goods = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->select();
        //判断库存是否足够
        $res = $this->apiIsEnough($AddData, $goods[0], $cartNum,$member_id);
        //var_dump($res);die;


        //如果是减个数 不判断库存
        if (!isset($action) || $action != 'minus') {
            if ($res['status'] == 0) {
                return array('msg' => $res['msg'], 'status' => 2);
            }
        }


        //购物车  是否有其他商品，获取该商品的 shipping

        /******************修复 3-4 日 冉************************/
        //$shipP = M('b2c_carts')->where(['local_id' => $local_id])->field('shipping')->find();
        $shipP = M('b2c_carts')->where(['local_id' => $local_id,'member_id' => $member_id])->field('shipping,mobile,store_dot_name,dot_id')->find();
        /**********************************************/

        if (!empty($shipP)) {
            $data['shipping'] = $shipP['shipping'];
            /******************修复 3-4 日 冉************************/
            $data['mobile'] = $shipP['mobile'];
            $data['store_dot_name'] = $shipP['store_dot_name'];
            $data['dot_id'] = $shipP['dot_id'];
            /**********************************************/
        } else {
            $data['shipping'] = 1;
        }


        if (empty($goods) && $action == 'minus') {
            return array('msg' => '成功', 'status' => 1);
        }
        if (empty($goods)) {
            $goodsarr = array();
            //加入购物车表
            $goodsarr['local_id'] = $local_id;
            $goodsarr['member_id'] = $member_id;
            $goodsarr['ischeck'] = $isCheck;
            $goodsarr['product_id'] = $pid;
            $goodsarr['cart_num'] = $cartNum;
            $goodsarr['goods_id'] = $goods_id;
            $goodsarr['time'] = time();
            $goodsarr['shipping'] = $data['shipping'];
            /******************修复 3-4 日 冉************************/
            $goodsarr['mobile'] = $data['mobile'];
            $goodsarr['dot_id'] = $data['dot_id'];
            $goodsarr['store_dot_name'] = $data['store_dot_name'];
            /**********************************************/
            $goodsarr['type'] = $res['type'];

            $rs = M('b2c_carts')->add($goodsarr);
            if (false !== $rs) {
                $status = $this->stroeMember($member_id, $local_id);
                if ($status === false) {
                    return array('msg' => '添加失败', 'status' => -1, 'code' => '会员门店关系表添加失败！');
                }
                //购物车情况
                $cartLast =   $this->getCartData($member_id);
                $total_goods_money = 0;
                foreach ($cartLast as $k=>$value){
                    $total_goods_money += $value['lp_fee'];
                }
                $total_goods_money = number_format($total_goods_money, 2, '.', '');

                return array('msg' => '添加成功', 'status' => 1,'money'=>$total_goods_money);
            }
        } else {
            //根据条件更新 num

            if (empty($action)) {
                $rs = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->setInc('cart_num', $cartNum);
            } elseif ($action == 'plus') {
                $rs = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->setInc('cart_num', 1);
            } elseif ($action == 'minus') {
                if ($goods[0]['cart_num'] <= 1) {
                    $rs = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->delete();
                } else {
                    $rs = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->setDec('cart_num', 1);
                }
            }
            $rs = M('b2c_carts')->where(array('member_id' => $member_id, 'product_id' => $pid, 'local_id' => $local_id))->save(['type' => $res['type']]);
            $status = $this->stroeMember($member_id, $local_id);
            if ($status === false) {
                return array('msg' => '添加失败', 'status' => -1, 'code' => '会员门店关系表添加失败！');
            }
            //购物车情况
            $cartLast =   $this->getCartData($member_id);
            $total_goods_money = 0;
            foreach ($cartLast as $k=>$value){
                $total_goods_money += $value['lp_fee'];
            }
            $total_goods_money = number_format($total_goods_money, 2, '.', '');
            return array('msg' => '添加成功', 'status' => 1,'money'=>$total_goods_money);
        }
        return array('msg' => '添加失败', 'status' => -1);

    }

    /**
     * 添加会员与门店的关系
     * @param $member_id
     * @param $local_id
     * @return bool|mixed
     */
    public function stroeMember($member_id, $local_id)
    {
        if (!$member_id || !$local_id) {
            return false;
        }
        $time = time();
        $sql = "INSERT INTO sdb_b2c_store_user(member_id,local_id,create_time) SELECT {$member_id},{$local_id},{$time} FROM DUAL
                WHERE NOT EXISTS(SELECT id FROM sdb_b2c_store_user WHERE member_id={$member_id} AND local_id={$local_id})";
        return M()->query($sql);
    }

    /**
     * 判断用户 + 选择数量 库存是否足够
     */
    public function isEnough($pid, $sid, $member_id)
    {

        /*$pid = I('post.pid');
        $sid = I('post.local_id');*/

        //库存
        $pStore = M('b2c_store_product')->where("product_id=$pid and local_id = $sid")
            ->field("store,freez")
            ->find();
        //该用户该商品购物车存在数量
        $cartStore = M('b2c_carts')->where("product_id=$pid and local_id = $sid and member_id = $member_id")
            ->field("cart_num")
            ->find();
        //echo M()->getLastSql();
        //加入数量+购物车数量 < 库存
        $totalNum = $cartStore['cart_num'] + I('post.buyNum');
        // echo  I('post.buyNum');

        if ($totalNum > ($pStore['store'] - $pStore['freez'])) {
            return array('msg' => '库存不足', 'status' => 0);
        } else {
            return array('msg' => '库存足够', 'status' => 1, 'type' => 0);
        }


    }

    /*
     * $AddData 点击操作提交数据
     * $cartData 该商品购物车数量
     * $buyNum 加入数量数量
     *
     */
    public function apiIsEnough($AddData, $cartData, $buyNum,$member_id)
    {
        //array('pid'=>$pid,'local_id'=>$local_id,'goods_id'=>$goods_id,'member_id'=>$member_id,'spid'=>$spid,'cartNum'=>$cartNum);
        //判断是否该商品处于闪购促销
        $m = new GoodsModel();
        $flashGoods = $m->checkGoodsIsStarBuy($AddData['spid']);

        if (!empty($flashGoods)) {
            //闪购商品
            //该用户已经购买该商品数量
            $is_user_buy = M('starbuy_count_member_buy')->where(['member_id'=>$member_id,'fg_id'=>$flashGoods['id']])->select();
            $red_buy = 0;
            foreach ($is_user_buy as $k=>$v){
                $red_buy += $v['count'];
            }
            /*print_r($flashGoods);
            echo $buyNum.'|'.$cartData['cart_num'].'|'.$flashGoods['limit'];*/
            if ($buyNum + $cartData['cart_num'] + $red_buy > $flashGoods['limit']) {

                $msg = array('msg' => '每个人最多能购买' . $flashGoods['limit'] . '个该商品', 'status' => 0);
                return $msg;
            }
            if ($flashGoods['initnum'] < $buyNum + $cartData['cart_num']) {
                $msg = array('msg' => '闪购库存不足', 'status' => 0);
            } else {
                $msg = array('msg' => '闪购库存足够', 'status' => 1, 'type' => 2);
            };

        } else {
            //普通商品
            $msg = $this->isEnough($AddData['pid'], $AddData['local_id'], $AddData['member_id']);
        }

        return $msg;

    }




    /**
     * 清除全部下架商品
     */
    public function clearGoods()
    {
        $data = $_POST;
    }


    /**
     * 清除下架商品
     */
    public function deleteGoods()
    {
        $result = M('b2c_carts')->where(['id' => $_POST['id']])->delete();

        if ($result) {
            return array('msg' => '清除成功', 'status' => 1);
        } else {
            return array('msg' => '参数错误', 'status' => 0);
        }

        return false;

    }






    /**
     * 购物车移出 勾选商品
     */
    public function removeCheck()
    {

        // $result =  M('b2c_carts')->where(['id'=>I('post.id')])->delete();
        $result = false;

        if ($result) {
            return array('msg' => '删除成功', 'status' => 1);
        } else {
            return array('msg' => '删除失败', 'status' => 0);
        }
    }
     


    public function changeCartShip($data)
    {
        $where['member_id'] = $data['member_id'];
        $where['local_id'] = $data['local_id'];
        $result = M('b2c_carts')->where($where)->save(array('shipping' => $data['shipping'], 'mobile' => '', 'dot_id' => '', 'store_dot_name' => ''));

        return $result;
    }

    public function setCartData($data)
    {

    }

    public function getCartData($member_id)
    {

        //店铺分组
        $group = M()->query("select 
	                        distinct a.local_id,local_name,store_lnt,store_lat,b.area_dispatch,b.province,b.is_self
                          from
                          (select distinct local_id from sdb_b2c_carts where member_id=$member_id)a
                          left outer join 
                          sdb_webpos_local_store b
                          on a.local_id=b.local_id");
        //用户地址

        $result1 = M()->query("select store_lnt,store_lat, area,name,addr,mobile from sdb_b2c_member_addrs where member_id=$member_id and def_addr=1");


        /*冉12-28*/

        $pPos = strpos($result1[0]['area'], ":");
        if (!empty($pPos)) {
            $addrr = explode(":", $result1[0]['area']);
            $result1[0]['area'] = $addrr[1];
        }
        $popps = strpos($result1[0]['area'], '/');
        $add_val = substr($result1[0]['area'], $popps + 1);
        $yf_addr = str_replace("/", "", $add_val);


        /*******************/

        //购物车商品列表
        $data = M()->query("select a.*,b.product_id,b.is_transport,d.name,d.spec_info,b.price,b.discount,c.goods_id,c.area_group_id,d.weight,b.store_status,b.marketprice,b.store,b.freez,b.goods_id,b.bn,b.store_pid,b.is_identity_card,b.is_identity_card_photo,b.import_duty,b.supplier_id from
                                (select * from sdb_b2c_carts where member_id=$member_id ) a
                                left outer join 
                                sdb_b2c_store_product b
								on a.product_id=b.product_id and a.local_id=b.local_id
								left outer join 
								sdb_b2c_goodsarea c
								on a.goods_id=c.goods_id
                                left outer join
                                sdb_b2c_products d 
                                on a.product_id=d.product_id");


        /**冉12-30 判断购物车地址，购物车商品*/
        $group['no_goods'] = 0;
        $group['no_address'] = 0;

        if (empty($data)) {
            $group['no_goods'] = 1;
        }
        if (empty($result1)) {
            $group['no_address'] = 1;
        }
        /**-------------------**/

        //$group['total_fee']=0;
        $group['out_time'] = array();
        $group['all_check'] = 1;
        $group['clearAll'] = 1;
        $group['store_ok'] = 1;
        $group['is_no_check'] = 0;//冉 2-6

        $tips = ''; //冉 12-22

        $x = 0;
        //print_r($group);
        foreach ($group as $k => &$v) {

            if( !is_numeric($k)){
                continue;
            }

            $v['lp_fee'] = 0;
            $v['shop_checkd'] = 1;
            $index = 0;
            //echo $result1[0]['store_lnt']."," .$result1[0]['store_lat']."," .$v['store_lnt']."," . $v['store_lat'].",";
            $v['distance'] = getDistance($result1[0]['store_lnt'], $result1[0]['store_lat'], $v['store_lnt'], $v['store_lat']);
            //echo $v['distance'];exit;
            $v['shipping'] = 1;
            $v['ship_fee'] = 0;
            $v['total_weight'] = 0;
            $v['store_dot_name'] = '';
            $isCstore = 'false';  //冉 商品库存不足，只取一个
            $v['zT_addr'] = '';//自提地址
            $v['expected_time'] = '';//自提时间
            $v['send_type'] = 0;//配送方式
            $v['local_total'] = 0;//门店应支付价格
            $v['checked_num'] = 0;//选择的数量
            $v['inner_type'] = 0;//配送计算方式 冉 12-28
            $v['default_local_id'] = 0;//配送计算方式 冉 12-28

            if($v['is_self']!=1){
                foreach ($data as $key => &$value) {
                    //普通商品
                    if ($value['type'] == 0 || $value['type'] == 2) {
                        if ($value['local_id'] == $v['local_id'] && $value['store_status'] == 'false') {
                            $group['out_time'][$x] = $value;
                            $x++;
                            continue;
                        }
                        if ($value['local_id'] == $v['local_id']) {
                            $group['clearAll'] = 0;

                            /*-------------------2-4  冉 购物车闪购商品---------------------*/


                            $m = new GoodsModel();
                            $flashproduct = $m->checkGoodsIsStarBuy($value['store_pid']);
                            $proGood = $m->checkGoodsIsPromotion($value['local_id'], $value['store_pid']);//促销商品
                            if ($value['type'] == 0) {
                                if (!empty($flashproduct)) {
                                    $value['final_price'] = $flashproduct['promotion_price'];
                                    $value['sg_id'] = $flashproduct['id'];
                                    $value['initnum'] = $flashproduct['initnum'];
                                    //更新该商品购物车的type=2
                                    M('b2c_carts')->where(['id' => $value['id']])->save(['type' => 2]);

                                } else {
                                    if (!empty($proGood)){
                                        //促销商品
                                        $value['final_price'] = $proGood['price'];
                                    }else{
                                        $value['final_price'] = $value['price'];
                                    }
                                }

                            }

                            if ($value['type'] == 2) {

                                if (!empty($flashproduct)) {
                                    $value['final_price'] = $flashproduct['promotion_price'];
                                    $value['sg_id'] = $flashproduct['id'];
                                    $value['initnum'] = $flashproduct['initnum'];
                                } else {
                                    //更新该商品购物车的type=0
                                    if (!empty($proGood)){
                                        //促销商品
                                        $value['final_price'] = $proGood['price'];
                                    }else{
                                        $value['final_price'] = $value['price'];
                                    }
                                    M('b2c_carts')->where(['id' => $value['id']])->save(['type' => 0]);
                                    //$value['final_price'] = $value['price'];
                                }

                            }
                            /*----------------------------------------*/

                            if ($value['shipping'] == 2 && $v['shipping'] == 1) {
                                $v['shipping'] = 2;
                            }
                            $v['store_dot_name'] = $value['store_dot_name'];
                            //算自提
                            if ($v['shipping'] == 2) {
                                //快递费还是默认为0
                                //算总费用
                                //$value['ischeck']='11111';
                                if ($value['ischeck'] == 1) {//勾选了的
                                    $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                    $group['is_no_check'] = 1; // 冉 2-6
                                } else {
                                    //未勾选
                                    $v['shop_checkd'] = 0;
                                    $group['all_check'] = 0;
                                }
                                $value['active'] = 1;

                                /***************冉12-24***自提地址 时间***********/
                                //自提 门店地址
                                if (!empty($value['dot_id'])) {
                                    $dotAddr = M('b2c_store_dot')->where(['dot_id' => $value['dot_id']])->field('addr')->find();
                                    $v['zT_addr'] = $dotAddr['addr'];
                                }
                                //自提 时间待定  时间
                                //$v['expected_time'] = "自提时间待定";

                                $mtype = new PayController();
                                $timemsg = $mtype->predictionTime(time(),3);

                                $v['expected_time'] = $timemsg;
                                $v['send_type'] = 3;
                                /****************************/

                            } else {//算快递

                                //范围内
                                if ($v['distance'] <= $v['area_dispatch'] * 1000) {
                                    /***************冉12-24***快递 时间***********/
                                    $mtype = new PayController();
                                    $timemsg = $mtype->predictionTime(time(),1);

                                    $v['expected_time'] = $timemsg;
                                    $v['send_type'] = 1;

                                    /***************冉12-24**************/
                                    //选中的，叠加重量，然后计算价格
                                    if ($value['ischeck'] == 1) {
                                        $v['total_weight'] += $value['weight'] * $value['cart_num'];
                                        //$v['ship_fee']=10;//算法
                                        $v['inner_type'] = 1; //冉 12-28   范围内门店快递

                                        $v['lp_fee'] += $value['final_price'] * $value['cart_num'];

                                        $group['is_no_check'] = 1; // 冉 2-6

                                    } else {//未选中，不管重量，不算价格
                                        $v['shop_checkd'] = 0;
                                        $group['all_check'] = 0;
                                    }
                                    $value['active'] = 1;
                                } else {//范围外
                                    //特殊商品
                                    if ($value['is_transport'] == 'false') {
                                        $value['active'] = 0;
                                    } else {//普通商品
                                        $value['active'] = 1;
                                        if ($value['ischeck'] == 1) {
                                            $v['total_weight'] += $value['weight'] * $value['cart_num'];
                                            //$v['ship_fee'] = 100;
                                            $v['inner_type'] = 2; //冉 12-28   范围外物流快递

                                            $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                            $group['is_no_check'] = 1; // 冉 2-6
                                        } else {
                                            $v['shop_checkd'] = 0;
                                            $group['all_check'] = 0;
                                        }
                                        /***************冉12-24***快递 时间***********/
                                        //范围外，当前时间+5
                                        /* $yuji = time() + 518400;
                                         $expected = date("Y-m-d", $yuji);
                                         $month = ((int)substr($expected, 5, 2));//取得月份
                                         $day = ((int)substr($expected, 8, 2));//取得几号
                                         $v['expected_time'] = "(预计" . $month . "月" . $day . "日前送达)";*/

                                        $mtype = new PayController();
                                        $timemsg = $mtype->predictionTime(time(),2,$result1[0]['area'],$v['province']);
                                        $v['expected_time'] = $timemsg;
                                        $v['send_type'] = 2;


                                        /***************冉12-24**************/


                                    }
                                }
                            }
                            /*-------------冉---购物车单个商品库存大于商品实际库存------激活商品------选中---*/

                            if ($value['cart_num'] > ($value['store'] - $value['freez']) && $value['active'] == 1 && $value['ischeck'] == 1 && $isCstore != 'true' && $value['type'] == 0) {
                                $tips = "购买商品中：" . $value['name'] . "库存不足！";
                                $group['store_ok'] = 0;
                                $isCstore = 'true';
                            } elseif ($value['type'] == 2) {

                                //print_r($flashproduct);

                                //闪购商品库存判断 2-03
                                $AddDatas = array('pid' => $value['product_id'], 'local_id' => $value['local_id'], 'goods_id' => $value['goods_id'], 'member_id' => $value['member_id'], 'spid' => $value['store_pid'], 'cartNum' => $value['cart_num']);
                                $c_num = $value['cart_num'] - 1;
                                $cartData = array('cart_num' => $c_num);

                                //判断库存是否足够
                                $res_sg = $this->apiIsEnough($AddDatas, $cartData, 1,$member_id);

                                //print_r($AddDatas);
                                if ($res_sg['status'] == 0) {
                                    // print_r($res_sg);
                                    $tips = "购买商品中：" . $value['name'] . $res_sg['msg'];
                                    $group['store_ok'] = 0;
                                    $isCstore = 'true';
                                }
                            }
                            /*-------------冉------------------*/


                            if (!isset($v['dot_id'])) {
                                $v['dot_id'] = $value['dot_id'];
                            }
                            if (!isset($v['mobile'])) {
                                $v['mobile'] = $value['mobile'];
                            }
                            $v['products'][$index] = $value;

                            //print_r($v['products'][$index]['product_id'].'/'.$index.'/'.$v['local_id'].'</br>');

                            if ($value['ischeck'] == 1 && $value['active'] == 1) {
                                $v['checked_num']++;
                            }


                            $index++;
                            //var_dump($index);
                        }


                    } //组合商品
                    else if ($value['type'] == 1) {
                        if ($value['local_id'] != $v['local_id']) {
                            continue;
                        }
                        $value['group_products'] = array();
                        $group_id = $value['group_id'];
                        $value['group_products'] = M()->query("select a.name,a.total_price,a.total_weight,state,start_time,end_time,b.product_id,c.name as product_name,d.price,b.num,c.spec_info,d.store_status,d.is_transport,d.marketprice,d.store,d.freez,d.bn,d.goods_id,c.weight,d.store_pid from
                            (select * from sdb_b2c_store_promotion_group where id=$group_id) a
                            left outer join 
                            sdb_b2c_store_promotion_group_item b 
                            on a.id=b.group_id
                            left outer join sdb_b2c_products c
                            on b.product_id=c.product_id
                            left outer join sdb_b2c_store_product d
                            on a.local_id=d.local_id and c.product_id=d.product_id"
                        );
                        $value['store_status'] = 'true';
                        $value['is_transport'] = 'true';
                        /*foreach($value['group_products'] as $k1=>&$v1){
                            $v1['id']=$value['id'];
                            $time=time();
                            $a=1;
                            if($time>$v1['end_time']){
                                $a=0;
                            }
                            if(($v1['state']=='0'||$a==0||$v1['store_status']=='false')&&$value['store_status']=='true'){
                                $value['store_status']='false';
                            }
                        }*/
                        for ($i = 0; $i < count($value['group_products']); $i++) {
                            $g_product =& $value['group_products'][$i];
                            $g_product['id'] = $value['id'];
                            $g_product['cart_num'] = $value['cart_num'];
                            $g_product['ischeck'] = $value['ischeck'];
                            $time = time();
                            $a = 1;
                            if ($time > $g_product['end_time']) {
                                $a = 0;
                            }
                            if (($g_product['state'] == '0' || $a == 0 || $g_product['store_status'] == 'false') && $value['store_status'] == 'true') {
                                $value['store_status'] = 'false';
                            }
                        }
                        if ($value['store_status'] == 'false') {
                            foreach ($value['group_products'] as $k1 => $v1) {
                                $v1['name'] = $v1['product_name'];
                                $group['out_time'][$x] = $v1;
                                $x++;
                            }
                            continue;
                            /*$group['out_time'][$x]=$value;
                            $x++;
                            continue;*/
                        }
                        foreach ($value['group_products'] as $k1 => $v1) {
                            if (!isset($value['final_price'])) {
                                $value['final_price'] = $v1['total_price'];
                            }
                            if (empty($value['weight'])) {
                                $value['weight'] = $v1['total_weight'];
                            }
                            if (empty($value['name'])) {
                                $value['name'] = $v1['name'];
                            }
                            if ($v1['is_transport'] == 'false' && $value['is_transport'] == 'true') {
                                $value['is_transport'] = 'false';
                            }

                        }
                        /******************修复 3-4 日 冉************************/
                        if ($value['shipping'] == 2 && $v['shipping'] == 1) {
                            $v['shipping'] = 2;
                        }
                        $v['store_dot_name'] = $value['store_dot_name'];
                        /******************************************/

                        //计算运费
                        if ($v['shipping'] == 2) {

                            //快递费还是默认为0
                            //算总费用

                            /***************冉12-24***自提地址 时间***********/
                            //自提 门店地址
                            if (!empty($value['dot_id'])) {
                                $dotAddr = M('b2c_store_dot')->where(['dot_id' => $value['dot_id']])->field('addr')->find();
                                $v['zT_addr'] = $dotAddr['addr'];
                            }
                            //自提 时间待定  时间

                            $mtype = new PayController();
                            $timemsg = $mtype->predictionTime(time(),3);

                            $v['expected_time'] = $timemsg;
                            $v['send_type'] = 3;
                            //$v['expected_time'] = "自提时间待定";
                            /****************************/


                            if ($value['ischeck'] == 1) {//勾选了的
                                $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                $group['is_no_check'] = 1; // 冉 2-6
                            } else {
                                //未勾选
                                $v['shop_checkd'] = 0;
                                $group['all_check'] = 0;
                            }
                            $value['active'] = 1;
                        } else {//算快递
                            //范围内
                            if ($v['distance'] <= $v['area_dispatch'] * 1000) {

                                /***************冉12-24***快递 时间***********/
                                //$v['expected_time'] = "(预计待定）";

                                $mtype = new PayController();
                                $timemsg = $mtype->predictionTime(time(),1);

                                $v['expected_time'] = $timemsg;
                                $v['send_type'] = 1;
                                /***************冉12-24**************/

                                //选中的，叠加重量，然后计算价格
                                if ($value['ischeck'] == 1) {
                                    $v['total_weight'] += $value['weight'] * $value['cart_num']; //冉12-28
                                    // $v['ship_fee']=10;//算法
                                    $v['inner_type'] = 1; //冉 12-28   范围内门店快递
                                    $group['is_no_check'] = 1; // 冉 2-6

                                    $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                } else {//未选中，不管重量，不算价格
                                    $v['shop_checkd'] = 0;
                                    $group['all_check'] = 0;
                                }
                                $value['active'] = 1;


                            } else {//范围外
                                //特殊商品

                                if ($value['is_transport'] == 'false') {
                                    $value['active'] = 0;
                                } else {//普通商品
                                    $value['active'] = 1;
                                    if ($value['ischeck'] == 1) {
                                        $v['total_weight'] += $value['weight'];
                                        //$v['ship_fee'] = 100;
                                        $v['inner_type'] = 2; //冉 12-28   范围内门店快递
                                        $group['is_no_check'] = 1; // 冉 2-6
                                        $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                    } else {
                                        $v['shop_checkd'] = 0;
                                        $group['all_check'] = 0;
                                    }
                                    /***************冉12-24***快递 时间***********/
                                    //范围外，当前时间+5
                                    /*$yuji = time() + 518400;
                                    $expected = date("Y-m-d", $yuji);
                                    $month = ((int)substr($expected, 5, 2));//取得月份
                                    $day = ((int)substr($expected, 8, 2));//取得几号
                                    $v['expected_time'] = "(预计" . $month . "月" . $day . "日前送达)";*/

                                    $mtype = new PayController();
                                    $timemsg = $mtype->predictionTime(time(),2,$result1[0]['area'],$v['province']);

                                    $v['expected_time'] = $timemsg;
                                    $v['send_type'] = 2;
                                    /***************冉12-24**************/


                                }
                            }
                        }
                        foreach ($value['group_products'] as $k2 => $v2) {
                            /*-------------冉---购物车单个商品库存大于商品实际库存------激活商品---促销组合是否有效---选中---*/
                            if ($v2['cart_num'] * $v2['num'] > ($v2['store'] - $v2['freez']) && $value['active'] == 1 && $value['ischeck'] == 1 && $isCstore != 'true') {
                                $group['store_ok'] = 0;
                                $tips = "购买商品中：" . $v2['product_name'] . "库存不足！";
                            }
                            /*-------------冉------------------*/

                        }

                        /*for($ii = 0;$ii<count($value['group_products']);$ii++){
                            $group['tips']="加老抽王酱油500m";
                        }*/

                        if (!isset($v['dot_id'])) {
                            $v['dot_id'] = $value['dot_id'];
                        }
                        if (!isset($v['mobile'])) {
                            $v['mobile'] = $value['mobile'];
                        }
                        //结束计算运费
                        $v['products'][$index] = $value;
                        //print_r($v['products'][$index]['product_id'].'/'.$index.'/'.$v['local_id'].'</br>');
                        if ($value['ischeck'] == 1 && $value['active'] == 1) {
                            $v['checked_num']++;
                        }
                        $index++;
                        //var_dump($index);
                    }
                }
                //if(isset($v['local_id'])&&$i==0){   12-29 冉

            }elseif($v['is_self']==1){

                //全国送
                //会员信息
                $member_info = M('b2c_members m')
                    ->join("left join sdb_b2c_temp_user  tu on tu.openid = m.openid")
                    ->where(['m.member_id'=>$member_id])->find();
                if(empty($member_info['source_local_id'])){
                    $v['default_local_id'] = 0;
                }else{
                    $v['default_local_id'] = $member_info['source_local_id'];
                }

                foreach ($data as $key => &$value) {
                    //普通商品
                    if ($value['type'] == 0 || $value['type'] == 2) {
                        if ($value['local_id'] == $v['local_id'] && $value['store_status'] == 'false') {
                            $group['out_time'][$x] = $value;
                            $x++;
                            continue;
                        }
                        if ($value['local_id'] == $v['local_id']) {
                            $group['clearAll'] = 0;

                            /*-------------------2-4  冉 购物车闪购商品---------------------*/
                            $m = new GoodsModel();
                            $flashproduct = $m->checkGoodsIsStarBuy($value['store_pid']);
                            $proGood = $m->checkGoodsIsPromotion($value['local_id'], $value['store_pid']);//促销商品
                            if ($value['type'] == 0) {
                                if (!empty($flashproduct)) {
                                    $value['final_price'] = $flashproduct['promotion_price'];
                                    $value['sg_id'] = $flashproduct['id'];
                                    $value['initnum'] = $flashproduct['initnum'];
                                    //更新该商品购物车的type=2
                                    M('b2c_carts')->where(['id' => $value['id']])->save(['type' => 2]);

                                } else {
                                    if (!empty($proGood)){
                                        //促销商品
                                        $value['final_price'] = $proGood['price'];
                                    }else{
                                        $value['final_price'] = $value['price'];
                                    }
                                }

                            }
                            if ($value['type'] == 2) {

                                if (!empty($flashproduct)) {
                                    $value['final_price'] = $flashproduct['promotion_price'];
                                    $value['sg_id'] = $flashproduct['id'];
                                    $value['initnum'] = $flashproduct['initnum'];
                                } else {
                                    //更新该商品购物车的type=0
                                    if (!empty($proGood)){
                                        //促销商品
                                        $value['final_price'] = $proGood['price'];
                                    }else{
                                        $value['final_price'] = $value['price'];
                                    }
                                    M('b2c_carts')->where(['id' => $value['id']])->save(['type' => 0]);
                                    //$value['final_price'] = $value['price'];
                                }

                            }
                            /*----------------------------------------*/


                            if ($v['shipping'] == 1) {

                                    $value['active_ident'] = 1;  //默认不需要验证
                                    //全国送只快递
                                    //是否身份证  是否上传身份证照片  不需要身份证
                                    //用户是否绑定了身份证，身份证照片
                                    if ($value['is_identity_card'] == 'true') {
                                        //查询该用户是否绑定身份证，并获取身份证是否上传照片
                                        if($value['is_identity_card_photo'] == 'true' && $member_info['identity_verifi'] == '1' && $member_info['identity_photo'] == ''){
                                            $value['active_ident'] = 2;  //身份证已经验证，但是未验证上传照片的身份证 需要上传照片
                                        }else if($value['is_identity_card_photo'] == 'true' && $member_info['identity_verifi'] == '2' ){
                                            $value['active_ident'] = 2;  //验证不通过，需要重新输入身份证跟照片
                                        }else if($value['is_identity_card_photo'] == 'true' && $member_info['identity_photo'] == ''){
                                            $value['active_ident'] = 2;  //身份证需要验证，并且验证上传身份证图片
                                        } else if($value['is_identity_card_photo'] == 'false' &&  $member_info['identity_name'] == '' && $member_info['identity_card_num'] == '' ){
                                            $value['active_ident'] = 0;  //身份证需要验证
                                        }else if($value['is_identity_card_photo'] == 'false' &&  $member_info['identity_name'] != '' && $member_info['identity_card_num'] != '' && $member_info['identity_verifi'] == '2' ){
                                            $value['active_ident'] = 0;  //验证失败，需要重新填写
                                        }
                                    }

                                    if ($value['ischeck'] == 1 && $value['active_ident'] == 1) {

                                        $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                                        $group['is_no_check'] = 1; // 冉 2-6


                                    } else {
                                        $v['shop_checkd'] = 0;
                                        $group['all_check'] = 0;
                                    }
                                    //范围外，当前时间+5
                                    $mtype = new PayController();
                                    $timemsg = $mtype->predictionTime(time(),2,$result1[0]['area'],$v['province']);
                                    $v['expected_time'] = $timemsg;
                                    $v['send_type'] = 2;
                                    /***************冉12-24**************/
                            }
                            /*-------------冉---购物车单个商品库存大于商品实际库存------激活商品------选中---*/

                            if ($value['cart_num'] > ($value['store'] - $value['freez']) && $value['active_ident'] == 1 && $value['ischeck'] == 1 && $isCstore != 'true' && $value['type'] == 0) {
                                $tips = "购买商品中：" . $value['name'] . "库存不足！";
                                $group['store_ok'] = 0;
                                $isCstore = 'true';
                            } elseif ($value['type'] == 2 && $value['active_ident'] == 1) {

                                //print_r($flashproduct);

                                //闪购商品库存判断 2-03
                                $AddDatas = array('pid' => $value['product_id'], 'local_id' => $value['local_id'], 'goods_id' => $value['goods_id'], 'member_id' => $value['member_id'], 'spid' => $value['store_pid'], 'cartNum' => $value['cart_num']);
                                $c_num = $value['cart_num'] - 1;
                                $cartData = array('cart_num' => $c_num);

                                //判断库存是否足够
                                $res_sg = $this->apiIsEnough($AddDatas, $cartData, 1,$member_id);

                                //print_r($AddDatas);
                                if ($res_sg['status'] == 0) {
                                    // print_r($res_sg);
                                    $tips = "购买商品中：" . $value['name'] . $res_sg['msg'];
                                    $group['store_ok'] = 0;
                                    $isCstore = 'true';
                                }
                            }
                            /*-------------冉------------------*/
                            if (!isset($v['dot_id'])) {
                                $v['dot_id'] = $value['dot_id'];
                            }
                            if (!isset($v['mobile'])) {
                                $v['mobile'] = $value['mobile'];
                            }
                            $v['products'][$index] = $value;
                            //print_r($v['products'][$index]['product_id'].'/'.$index.'/'.$v['local_id'].'</br>');

                            if ($value['ischeck'] == 1 && $value['active_ident'] == 1) {
                                $v['checked_num']++;
                            }
                            $index++;
                        }


                    } //组合商品
                    else if ($value['type'] == 1) {

                        if ($value['local_id'] != $v['local_id']) {
                            continue;
                        }
                        //组合商品必须是同一个供应商


                        $value['group_products'] = array();
                        $group_id = $value['group_id'];
                        $value['group_products'] = M()->query("select a.name,a.total_price,a.total_weight,state,start_time,end_time,b.product_id,c.name as product_name,d.price,b.num,c.spec_info,d.store_status,d.is_transport,d.marketprice,d.store,d.freez,d.bn,d.goods_id,c.weight,d.store_pid,d.is_identity_card,d.is_identity_card_photo,d.import_duty,d.supplier_id from
                            (select * from sdb_b2c_store_promotion_group where id=$group_id) a
                            left outer join 
                            sdb_b2c_store_promotion_group_item b 
                            on a.id=b.group_id
                            left outer join sdb_b2c_products c
                            on b.product_id=c.product_id
                            left outer join sdb_b2c_store_product d
                            on a.local_id=d.local_id and c.product_id=d.product_id"
                        );
                        $value['store_status'] = 'true';
                        $value['is_transport'] = 'true';
                        $value['active_ident'] = 1;  //已经验证不需要再次输入身份证
                        for ($i = 0; $i < count($value['group_products']); $i++) {
                            $g_product =& $value['group_products'][$i];
                            $g_product['id'] = $value['id'];
                            $g_product['cart_num'] = $value['cart_num'];
                            $g_product['ischeck'] = $value['ischeck'];
                            $time = time();
                            $a = 1;
                            if ($time > $g_product['end_time']) {
                                $a = 0;
                            }
                            if (($g_product['state'] == '0' || $a == 0 || $g_product['store_status'] == 'false') && $value['store_status'] == 'true') {
                                $value['store_status'] = 'false';
                            }
                        }
                        if ($value['store_status'] == 'false') {
                            foreach ($value['group_products'] as $k1 => $v1) {
                                $v1['name'] = $v1['product_name'];
                                $group['out_time'][$x] = $v1;
                                $x++;
                            }
                            continue;
                        }
                        foreach ($value['group_products'] as $k1 => $v1) {
                            if (!isset($value['final_price'])) {
                                $value['final_price'] = $v1['total_price'];
                            }
                            if (empty($value['weight'])) {
                                $value['weight'] = $v1['total_weight'];
                            }
                            if (empty($value['name'])) {
                                $value['name'] = $v1['name'];
                            }
                            if ($v1['is_transport'] == 'false' && $value['is_transport'] == 'true') {
                                $value['is_transport'] = 'false';
                            }


                        }
                        //组合商品是否上传身份证，照片
                        $arr_gp = array();

                        $value['active_ident'] = 1;  //默认不需要验证
                        foreach ($value['group_products'] as $k1 => $v1) {

                            if ($v1['is_identity_card'] == 'true') {

                                //查询该用户是否绑定身份证，并获取身份证是否上传照片
                                if ($v1['is_identity_card_photo'] == 'true' && $member_info['identity_verifi'] == '1' && $member_info['identity_photo'] == '') {
                                    array_push($arr_gp, 2);//身份证已经验证，但是未验证上传照片的身份证 需要上传照片
                                } else if ($v1['is_identity_card_photo'] == 'true' && $member_info['identity_verifi'] == '2') {
                                    array_push($arr_gp, 2);//验证不通过，需要重新输入身份证跟照片
                                } else if ($v1['is_identity_card_photo'] == 'true' && $member_info['identity_photo'] == '') {
                                    array_push($arr_gp, 2); //身份证需要验证，并且验证上传身份证图片
                                }  else if ($v1['is_identity_card_photo'] == 'false' && $member_info['identity_name'] == '' && $member_info['identity_card_num'] == '') {
                                    array_push($arr_gp, 0);  //身份证需要验证
                                } else if ($v1['is_identity_card_photo'] == 'false' && $member_info['identity_name'] != '' && $member_info['identity_card_num'] != '' && $member_info['identity_verifi'] == '2') {
                                    array_push($arr_gp, 0); //验证失败，需要重新填写
                                }
                            }
                            //供应商ID
                            $value['supplier_id'] =  $v1['supplier_id'];
                        }

                        if (in_array(2,$arr_gp)){
                            $value['active_ident'] = 2;
                        }elseif (in_array(0,$arr_gp)){
                            $value['active_ident'] = 0;
                        }


                        //进口税
                        //普通商品
                            if ($value['ischeck'] == 1  && $value['active_ident'] == 1) {
                                $group['is_no_check'] = 1; // 冉 2-6

                                $v['lp_fee'] += $value['final_price'] * $value['cart_num'];
                            } else {
                                $v['shop_checkd'] = 0;
                                $group['all_check'] = 0;
                            }
                            /***************冉12-24***快递 时间***********/
                            //范围外，当前时间+5
                            $mtype = new PayController();
                            $timemsg = $mtype->predictionTime(time(),2,$result1[0]['area'],$v['province']);

                            $v['expected_time'] = $timemsg;
                            $v['send_type'] = 2;
                            /***************冉12-24**************/

                            foreach ($value['group_products'] as $k2 => &$v2) {
                                /*-------------冉---购物车单个商品库存大于商品实际库存------激活商品---促销组合是否有效---选中---*/
                                if ($v2['cart_num'] * $v2['num'] > ($v2['store'] - $v2['freez']) && $value['active_ident'] == 1 && $value['ischeck'] == 1 && $isCstore != 'true') {
                                    $group['store_ok'] = 0;
                                    $tips = "购买商品中：" . $v2['product_name'] . "库存不足！";
                                }
                                /*-------------冉------------------*/
                                $v2['active_ident'] = $value['active_ident'];
                            }
                            if (!isset($v['dot_id'])) {
                                $v['dot_id'] = $value['dot_id'];
                            }
                            if (!isset($v['mobile'])) {
                                $v['mobile'] = $value['mobile'];
                            }
                            //结束计算运费
                            $v['products'][$index] = $value;
                            if ($value['ischeck'] == 1 && $value['active_ident'] == 1) {
                                $v['checked_num']++;
                            }
                            $index++;

                        }

                    }

            }

            if (isset($v['local_id']) && $index == 0) {  // 12-29 冉
                //echo $v['local_id'];
                unset($group[$k]);
                continue;
            }

            //计算运费 12-28 冉
            if ($v['inner_type'] == 1) {
                $v['ship_fee'] = $this->cal($v['total_weight'], '', $v['local_id'], $v['inner_type']);
            } elseif ($v['inner_type'] == 2) {
                $v['ship_fee'] = $this->cal($v['total_weight'], $yf_addr, $v['local_id'], $v['inner_type']);
            }
            $v['ship_fee'] = number_format($v['ship_fee'], 2, '.', '');
            /**************************/
            $v['local_total'] = $v['ship_fee'] + $v['lp_fee'];
            $group['total_fee'] += $v['local_total'];
            $group['goods_total_fee'] += $v['lp_fee'];


        }
        //print_r($group);
        //$group['total_fee'] = $aaa;

        $group['address'] = $result1[0];
        $group['tips'] = $tips;
        //echo '<pre>';
       //print_r($group);

        return $group;
    }




    /**
     * @param $weight重量
     * @param $dlytmp 模板 运费
     * @param $local_id 门店ID
     * @param $type 类型  1 范围内门店配送，2快递配送
     * @param $addr 地址
     */
    public function cal($weight, $addr, $local_id, $type)
    {

        if ($type == 1) {
            //范围内，送货上门费用模板
            $dlytmp = M('b2c_dlyyctmp')->where(['local_id' => $local_id])->field('firstunit,continueunit,firstprice,continueprice')->find();
        } elseif ($type == 2) {

            //范围外
            /*$pos = strpos($addR['area'],"/");
            $text = substr($addR['area'],$pos+1);
            $address = str_replace("/","",$text);*/
            $dlytmp = M('b2c_dlytmp')->where(array('local_id' => $local_id, 'active' => '1', 'area_group_id' => array('like', "%" . $addr . "%")))->field('firstunit,continueunit,firstprice,continueprice')->find();

            if (empty($dlytmp)) {
                $dlytmp = M('b2c_dlytmp')->where(array('local_id' => $local_id, 'is_def' => 1, 'active' => '1'))->find();
            }
        }

        if (empty($dlytmp)) {
            $cost_freight = 0;
            return $cost_freight;
        }
        if ($weight <= ($dlytmp['firstunit'] * 1000)) {
            $cost_freight = $dlytmp['firstprice'];
        } else {
            $price = ceil(($weight - ($dlytmp['firstunit'] * 1000)) / ($dlytmp['continueunit'] * 1000)) * $dlytmp['continueprice'];
            $cost_freight = $dlytmp['firstprice'] + $price;
        }

        return $cost_freight;
    }


}